package com.isis.servlet;

import java.io.IOException;


import javax.servlet.ServletException;
import javax.servlet.http.*;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.isis.jdo.crud.ManagerDataStore;
import com.isis.service.MailService;
import com.isis.service.SendChatMessage;


@SuppressWarnings("serial")
public class Authentification extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		String emailAdmin="edaheron@gmail.com";
		
		
		String thisPage = request.getRequestURI(); // l'URL de cette page
	
		if (user != null) { // L'utilisateur est déjà  authentifié
			String logoutURL = userService.createLogoutURL(thisPage); // l'URL de la page de logout
			request.setAttribute("logoutURL",logoutURL);
			request.setAttribute("email",user.getEmail());
			ManagerDataStore mds= new ManagerDataStore();
			int nbConnexion =mds.countUserConnexion(user.getEmail());
			String repChatMessage=null;
			String repChatMessageControl = request.getParameter("repChatMessageControl");
			if(repChatMessageControl==null){
				repChatMessageControl="";
			}
			
			repChatMessage="<p> C'est votre "+nbConnexion+" fois que vous vous connectez à cette application</p>";
			repChatMessage+=repChatMessageControl;
//			if((nbConnexion%10)==0){
//				SendChatMessage chatMessage=new SendChatMessage(emailAdmin);
//				repChatMessage += chatMessage.sendMessageToChat("L'utilisateur "+user.getEmail()+" viens de se connecter pour la "+nbConnexion+" fois à l'application ISISProject+");
//				
//			}
			String message = request.getParameter("message");
			String subject = request.getParameter("subject");
			if(message!=null || subject!=null){
				MailService ms=new MailService();
				int confirmationMail =ms.sendMail(user.getEmail(), emailAdmin, subject, message);
				request.setAttribute("confirmationMail",confirmationMail);
			}else{
				request.setAttribute("confirmationMail",0);
			}
			
			request.setAttribute("repChatMessage",repChatMessage);
			
			
			
			getServletContext().getRequestDispatcher("/accueil.jsp").forward(request, response);
			
		} else {			
			String loginURL = userService.createLoginURL("/authentificationControl"); // l'URL de la page de login
			request.setAttribute("loginPage",loginURL);
            getServletContext().getRequestDispatcher("/accueilConnexion.jsp").forward(request, response);
		}
		
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		
		this.doGet(request, response);
	}
}